import React, { useState, useEffect } from "react";
import {
  Modal,
  Typography,
  Space,
  Tag,
  Button,
  List,
  Avatar,
  Input,
  Form,
  message,
  Divider,
  Tooltip,
  Result,
} from "antd";
import {
  UserOutlined,
  LikeOutlined,
  RobotOutlined,
  SendOutlined,
  LockOutlined,
} from "@ant-design/icons";
import styled from "styled-components";
import type {
  DiscussionPost,
  DiscussionReply,
} from "../../../../common/types/discussion";
import { useUser } from "../../../../../contexts/UserContext";
import PermissionGuard from "../../../../../components/PermissionGuard";
import discussionService from "../../../../../services/discussion";

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;

const ReplyWrapper = styled.div`
  background-color: #f5f5f5;
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 16px;
`;

const AIReplyWrapper = styled(ReplyWrapper)`
  background-color: #f0f5ff;
  border-left: 4px solid #1890ff;
`;

interface DiscussionDetailProps {
  discussionId: string;
  onClose: () => void;
}

const DiscussionDetail: React.FC<DiscussionDetailProps> = ({
  discussionId,
  onClose,
}) => {
  const { user } = useUser();
  const [loading, setLoading] = useState(true);
  const [discussion, setDiscussion] = useState<DiscussionPost>();
  const [form] = Form.useForm();

  useEffect(() => {
    loadDiscussion();
  }, [discussionId]);

  const loadDiscussion = async () => {
    setLoading(true);
    try {
      const data = await discussionService.getDiscussion(discussionId);
      if (data) {
        setDiscussion(data);
      } else {
        message.error("讨论不存在");
        onClose();
      }
    } catch (error) {
      message.error("加载讨论详情失败");
      console.error("加载讨论详情失败:", error);
      onClose();
    } finally {
      setLoading(false);
    }
  };

  const handleReply = async (values: { content: string }) => {
    if (!discussion || !user) return;

    try {
      const reply = await discussionService.addReply(discussion.id, {
        content: values.content,
        author: {
          id: String(user.id),
          name: user.name,
          role: user.role,
        },
        likes: 0,
      });

      setDiscussion((prev) => {
        if (!prev) return prev;
        return {
          ...prev,
          replies: [...prev.replies, reply],
        };
      });

      form.resetFields();
      message.success("回复成功！");
    } catch (error) {
      message.error("回复失败，请重试");
      console.error("回复失败:", error);
    }
  };

  const handleLike = async (type: "post" | "reply", id: string) => {
    if (!user) {
      message.warning("请先登录");
      return;
    }

    try {
      if (type === "post") {
        await discussionService.likeDiscussion(id, String(user.id));
      } else {
        await discussionService.likeReply(discussionId, id, String(user.id));
      }
      loadDiscussion();
    } catch (error) {
      message.error("点赞失败，请重试");
      console.error("点赞失败:", error);
    }
  };

  return (
    <Modal
      title="讨论详情"
      open={true}
      onCancel={onClose}
      width={800}
      footer={null}
    >
      {discussion && (
        <div>
          <Title level={4}>{discussion.title}</Title>
          <Space style={{ marginBottom: 16 }}>
            <Avatar icon={<UserOutlined />} />
            <Text>{discussion.author.name}</Text>
            <Tag
              color={discussion.author.role === "teacher" ? "blue" : undefined}
            >
              {discussion.author.role === "teacher" ? "教师" : "学生"}
            </Tag>
            <Text type="secondary">发布于 {discussion.createTime}</Text>
            {discussion.tags.map((tag) => (
              <Tag key={tag}>{tag}</Tag>
            ))}
          </Space>

          <Paragraph>{discussion.content}</Paragraph>

          <Space style={{ marginBottom: 24 }}>
            <PermissionGuard
              permission="discussion.like"
              fallback={
                <Tooltip title="登录后即可点赞">
                  <Button icon={<LikeOutlined />} disabled>
                    {discussion.likes} 赞
                  </Button>
                </Tooltip>
              }
            >
              <Button
                type="text"
                icon={<LikeOutlined />}
                onClick={() => handleLike("post", discussion.id)}
              >
                {discussion.likes} 赞
              </Button>
            </PermissionGuard>
          </Space>

          {discussion.aiResponse && (
            <AIReplyWrapper>
              <Space align="start">
                <Avatar
                  icon={<RobotOutlined />}
                  style={{ backgroundColor: "#1890ff" }}
                />
                <div>
                  <Space>
                    <Text strong>AI 助手</Text>
                    <Text type="secondary">
                      回复于 {discussion.aiResponse.createTime}
                    </Text>
                  </Space>
                  <Paragraph style={{ marginTop: 8 }}>
                    {discussion.aiResponse.content}
                  </Paragraph>
                </div>
              </Space>
            </AIReplyWrapper>
          )}

          <Divider orientation="left">全部回复</Divider>

          <List
            itemLayout="vertical"
            dataSource={discussion.replies}
            renderItem={(reply) => (
              <ReplyWrapper key={reply.id}>
                <Space align="start">
                  <Avatar icon={<UserOutlined />} />
                  <div style={{ flex: 1 }}>
                    <Space>
                      <Text strong>{reply.author.name}</Text>
                      <Tag
                        color={
                          reply.author.role === "teacher" ? "blue" : undefined
                        }
                      >
                        {reply.author.role === "teacher" ? "教师" : "学生"}
                      </Tag>
                      <Text type="secondary">回复于 {reply.createTime}</Text>
                    </Space>
                    <Paragraph style={{ marginTop: 8 }}>
                      {reply.content}
                    </Paragraph>
                    <PermissionGuard
                      permission="discussion.like"
                      fallback={
                        <Tooltip title="登录后即可点赞">
                          <Button icon={<LikeOutlined />} disabled>
                            {reply.likes} 赞
                          </Button>
                        </Tooltip>
                      }
                    >
                      <Button
                        type="text"
                        icon={<LikeOutlined />}
                        onClick={() => handleLike("reply", reply.id)}
                      >
                        {reply.likes} 赞
                      </Button>
                    </PermissionGuard>
                  </div>
                </Space>
              </ReplyWrapper>
            )}
          />

          <Divider />

          <PermissionGuard
            permission="discussion.reply"
            fallback={
              <Result
                icon={<LockOutlined />}
                title="需要登录后才能回复"
                extra={
                  <Button type="primary" href="/login">
                    去登录
                  </Button>
                }
              />
            }
          >
            <Form form={form} onFinish={handleReply}>
              <Form.Item
                name="content"
                rules={[{ required: true, message: "请输入回复内容" }]}
              >
                <TextArea
                  rows={4}
                  placeholder="写下你的回复..."
                  maxLength={1000}
                  showCount
                />
              </Form.Item>
              <Form.Item style={{ marginBottom: 0, textAlign: "right" }}>
                <Button
                  type="primary"
                  htmlType="submit"
                  icon={<SendOutlined />}
                >
                  发表回复
                </Button>
              </Form.Item>
            </Form>
          </PermissionGuard>
        </div>
      )}
    </Modal>
  );
};

export default DiscussionDetail;
